package com.hadoopSpark.application.test;

import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.spec.PKCS8EncodedKeySpec;

import javax.net.ssl.SSLContext;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;

import com.aliyun.configuration.ConfigurationTool;
import com.common.constant.Constant;

/*
 * 练习，在阿里云，创建hadoop 应用
 * 这个是，第一个版本，
 */
public class CreateHadoopAppV1 {
	
	public static void main(String[] args) {
		 final char[] KEY_STORE_PASSWD = "".toCharArray();
		 //get certificate address
		 try {
			 Path caCertPath = Paths.get(ConfigurationTool.getProperties(Constant.CA_CERT_PATH));
			 Path clientCertPath = Paths.get(ConfigurationTool.getProperties(Constant.CLIENT_CERT_PATH));
			 Path clientKeyPath = Paths.get(ConfigurationTool.getProperties(Constant.CLIENT_KEY_PATH));
			 
			 final CertificateFactory cf = CertificateFactory.getInstance("X.509");
			 final Certificate caCert = cf.generateCertificate(Files.newInputStream(caCertPath));
			 final Certificate clientCert = cf.generateCertificate(Files.newInputStream(clientCertPath));
			 @SuppressWarnings("resource")
			 final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser(Files.newBufferedReader(clientKeyPath, Charset.defaultCharset())).readObject();
			 System.out.println("----------------------------------");
			 final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(clientKeyPair.getPrivateKeyInfo().getEncoded());
			 
			 final KeyFactory kf = KeyFactory.getInstance("RSA");
			 
			 final PrivateKey clientKey = kf.generatePrivate(spec);
			 
			 //设置信任的证书
			 final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
			 trustStore.load(null, null);
			 trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);
			 
			 //设置秘钥
			 final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
			 keyStore.load(null, null);
			 keyStore.setCertificateEntry("client", clientCert);
			 keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWD, new Certificate[]{clientCert});
			 
			 SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore,null)
					 .loadKeyMaterial(keyStore, KEY_STORE_PASSWD).build();
			 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.getDefaultHostnameVerifier());

			 //httpclient链接
			 CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
			 
			 
			 
			 
//			 HttpGet httpGet = new HttpGet(ConfigurationTool.getProperties(Constant.ALIYUN_URL)+"hadoop6");
			 
//			 HttpRequest httpRequest = new HttpRequest(ConfigurationTool.getProperties(Constant.ALIYUN_URL));
//			 
//			 httpRequest.setMethod(MethodType.POST);
			 
			 
			 
			 HttpPost httpPost = new HttpPost(ConfigurationTool.getProperties(Constant.ALIYUN_PROJECTS_URL));
			 
			 httpPost.addHeader("Content-type","application/json;charset=UTF-8");
			 
			 String requestEntityStr = 
					 "{\"name\":\"hadoop7\","
							+ "\"description\":\"This is a test application\","
							+ "\"template\":\"master: \\r\\n image: 'registry.aliyuncs.com/registry_yxkj/hadoop_spark:1.0'\","
							+ "\"version\":\"1.0\"}";
			 StringEntity stringEntity = new StringEntity(requestEntityStr, Charset.forName("UTF-8"));
			 
			 httpPost.setEntity(stringEntity);

			 //使用客户端向服务器发送数据
			 HttpResponse httpResponse = httpClient.execute(httpPost);
			 System.out.println(httpResponse.getStatusLine().getStatusCode());
			 
				HttpEntity resultEntity = httpResponse.getEntity();
				
				//返回结果是，服务器上，返回来的是json字符串数据
				String strResultEntity = EntityUtils.toString(resultEntity);
				
				System.out.println(strResultEntity);
			 Header contentEncoding = resultEntity.getContentEncoding();
			 System.out.println(contentEncoding.getName()+"--->"+contentEncoding.getValue());
			 
			 
			 
			 
//			 JSONArray arrJson = new JSONArray();
//			 JSONObject objJson = new JSONObject();
//			 objJson.put("name", "hadoop7");
//			 objJson.put("description", "this is a test application");
////			 objJson.put("template", "master-hadoop:\r\n  image:registry.aliyuncs.com/registry_yxkj/hadoop_spark:1.0");
//			 arrJson.add(objJson);
			 
	
			 
			 
			 System.out.println("----------------3------------------");
			 
//			 List<NameValuePair> appKYList = new ArrayList<NameValuePair>();
//			 NameValuePair appName = new BasicNameValuePair("name","hadoop7");
//			 System.out.println("----------------4------------------");
//			 NameValuePair appDes = new BasicNameValuePair("description","hadoop, one master node , two slave node");
//			 String template = "master-hadoop :\r\n    "
//			 		+ "	image : registry.aliyuncs.com/registry_yxkj/hadoop_spark:1.0";
//			 
//			 NameValuePair appTemplate = new BasicNameValuePair("template",template);
//			 NameValuePair appVersion = new BasicNameValuePair("version","1.1");
//			 
//			 appKYList.add(appName);
////			 appKYList.add(appDes);
////			 appKYList.add(appTemplate);
////			 appKYList.add(appVersion);
//			 System.out.println("----------------5------------------");
//			 
//			 HttpEntity httpEntity = new UrlEncodedFormEntity(appKYList, "UTF-8");
//			 System.out.println("----------------6------------------");
//			 
//			 httpPost.setEntity(httpEntity);
//			 System.out.println("----------------7------------------");
			 

			 
			 
			 
			 System.out.println("----------------8------------------");
			 if (httpResponse.getStatusLine().getStatusCode() == 200) {
//				HttpEntity resultEntity = httpResponse.getEntity();
//				
//				//返回结果是，服务器上，返回来的是json字符串数据
//				String strResultEntity = EntityUtils.toString(resultEntity);
//				
//				System.out.println(strResultEntity);
				System.out.println("SB--------------------> OK");
			} else {
				System.out.println(httpResponse.getStatusLine().getStatusCode());
				System.out.println("SB--------------------> 错啦");
			}
		
			} catch (Exception e) {
				e.printStackTrace();
			}
	}
}
		
		
		
